package com.zyzd.baseretrofit.dialog;

import android.content.Context;

import com.zyzd.baseretrofit.interf.ProgressCancelListener;
import com.zyzd.baseretrofit.interf.SubscriberOnNextListener;
import com.zyzd.commontools.log.TLog;

import rx.Subscriber;

/**
 * Created by 李宗源 on 2017/4/25.
 */

public class ProgressSubscriber<T> extends Subscriber<T> implements ProgressCancelListener {

    public SubscriberOnNextListener mSubscriberOnNextListener;
    public Context mContext;
    public ProgressDialogHandler mProgressDialogHandler;

    public ProgressSubscriber(SubscriberOnNextListener subscriberOnNextListener, Context context) {
        mSubscriberOnNextListener = subscriberOnNextListener;
        mContext = context;
        mProgressDialogHandler = new ProgressDialogHandler(context, this, true);
    }

    private void showProgressDialog() {
        if (mProgressDialogHandler != null) {
            mProgressDialogHandler.obtainMessage(ProgressDialogHandler.SHOW_PROGRESS_DIALOG).sendToTarget();
        }
    }

    private void dismissProgressDialog() {
        if (mProgressDialogHandler != null) {
            mProgressDialogHandler.obtainMessage(ProgressDialogHandler.DISMISS_PROGRESS_DIALOG).sendToTarget();
            mProgressDialogHandler = null;
        }
    }

    @Override
    public void onStart() {
        showProgressDialog();
    }

    @Override
    public void onCompleted() {
        dismissProgressDialog();
        TLog.d("zyzd", "ProgressSubscriber>>onCompleted--> ");
    }

    @Override
    public void onError(Throwable e) {
        dismissProgressDialog();
        TLog.d("zyzd", "ProgressSubscriber>>onError--> " + e.getMessage());
    }

    @Override
    public void onNext(T t) {
        mSubscriberOnNextListener.onNext(t);
    }

    @Override
    public void onCancelProgress() {
        if (!this.isUnsubscribed()) {
            this.unsubscribe();
        }
    }

}
